<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2016/12/28
 * Time: 16:16
 */

namespace SDXApi\Repositories;


use SDXApi\Model\GoodsModel;
use SDXApi\Model\GoodspreselltimeModel;
use SDXApi\Model\GoodsstorageModel;
use SDXApi\Model\GoodsWidModel;
use SDXApi\Service\BuyNowNoticeService;

/**
 * 秒杀数据处理仓库
 * Class BuyNowGoodsRepository
 * @package SDXApi\Repositories
 */
class BuyNowGoodsRepository
{
    /**
     * @var
     */
    public $wid;

    /**
     * @var
     */
    public $userId;

    /**
     * @var GoodsWidModel
     */
    protected static $goodsWidModel;


    /**
     * @var GoodsstorageModel
     */
    protected static $goodsStorageModel;

    /**
     * @var GoodsModel
     */
    protected static $goodsModel;

    /**
     * @var BuyNowNoticeService
     */
    protected static $buyNowNoticeService;

    /**
     * @var GoodspreselltimeModel
     */
    protected static $goodsPresellTimeModel;


    /**
     * @var array
     */
    protected $message = array();

    /**
     * 注入实例
     * BuyNowGoodsRepository constructor.
     * @param $userId
     * @param int $wid
     */
    public function __construct($userId = 0, $wid = 8)
    {
        self::$goodsWidModel = new GoodsWidModel();
        self::$goodsStorageModel = new GoodsstorageModel();
        self::$goodsModel = new GoodsModel();
        self::$buyNowNoticeService = new BuyNowNoticeService();
        self::$goodsPresellTimeModel = new GoodspreselltimeModel();

        $this->wid = $wid;
        $this->userId = $userId;
    }


    /**
     * Created by Jerry
     * @param $goods
     * @return bool|array
     */
    public function formatBuyNowGoods($goods)
    {
        if (empty($goods)) {
            return false;
        }

        foreach ($goods as $key => $value) {
            $goodsInfo = $this->findBuyNowGoodsInfoByGoodsId($value['goods_id']);

            if (empty($goodsInfo)) {
                unset($goods[$key]);
                continue;
            }

            $goodsNumber = $this->findGoodsStorageById($value['goods_id']);

            $goods[$key]['goods_name'] = $goodsInfo['goods_name'];
            $goods[$key]['original_img'] = img_init($goodsInfo['original_img']);
            $goods[$key]['goods_img'] =  img_init($goodsInfo['goods_img']);
            $goods[$key]['goods_thumb'] = img_init($goodsInfo['goods_thumb']);

            $goods[$key]['goods_brief'] = $goodsInfo['goods_brief'];
            $goods[$key]['is_presell'] = ($goodsInfo['is_presell'] == 1) ? $this->getGoodsStorageGoodsNumber($value['goods_id']) : $goodsInfo['is_presell'];


            if ($goods[$key]['is_presell'] == 1) {
//				预售商品使用虚拟库存
                $goods[$key]['goods_number'] = $goodsInfo['goods_number'];
            }
            else
            {
//				现售商品使用实际库存
                $goods[$key]['goods_number'] = $goodsNumber;
            }

            if ($goods[$key]['is_presell']) {
                if ($goodsInfo['delivery_type'] == 1) {
                    if (self::$goodsPresellTimeModel->check_shipping_goodspreselltime($value['goods_id'])) {
                        $time = time();
                        $shippingTime = self::$goodsPresellTimeModel->check_shippingtime($value['goods_id'], $time);

                        if ($shippingTime) {
                            $goods[$key]['preselltimeres'] = array(
                                'delivery_time'	=>	$shippingTime,
                            );
                        }
                        else{
                            $goods[$key]['preselltimeres'] = array(
                                'delivery_time'	=>	'',
                            );
                        }
                    }
                    else{
                        $goods[$key]['preselltimeres'] = array(
                            'delivery_time'	=>	'',
                        );
                    }
                }
                else if($goodsInfo['delivery_type'] == 2) {
                    if ($goodsInfo['delivery_cycle']>=0) {
                        $gmd = local_date('Y-m-d', gmtime());

                        $goodsPresellTime = local_date('Y-m-d H:i:s', local_strtotime($gmd . ' +' . $goodsInfo['delivery_cycle'] . ' day ' . C('DEFAULT_PRESELL_TIME_H')));
                        $goods[$key]['preselltimeres'] = array(
                            'delivery_time' => $goodsPresellTime,
                        );
                    }
                    else{
                        $goods[$key]['preselltimeres'] = array(
                            'delivery_time'	=>	'',
                        );
                    }
                }
                else{
                    $goods[$key]['preselltimeres'] = array(
                        'delivery_time'	=>	'',
                    );
                }
            }
            else{
                $goodsStorage = self::$goodsStorageModel->get_warehous_goods($this->wid, $value['goods_id']);
                if ($goodsStorage) {
                    $goods[$key]['goods_number'] = $goodsStorage['practical_num'];
                }
                else{
                    $goods[$key]['goods_number'] = 0;
                }
                $goods[$key]['preselltimeres'] = array('delivery_time' => '');
            }

            $goods[$key]['warn_number'] = $goodsInfo['warn_number'];

            if ($goods[$key]['goods_number'] == 0) {
                $goods[$key]['is_book_goods'] = $this->goodsBook($value['goods_id']);
            }

//			登录已未登录商品价格
            if ($this->userId) {
                $goods[$key]['market_price'] = self::$goodsModel->get_vip_price_for_all($value['goods_id'], 1);
                $goods[$key]['vip_price'] = self::$goodsModel->get_vip_price($value['goods_id'], $this->userId);
                $goods[$key]['true_vip_price'] = self::$goodsModel->get_vip_price_for_all($value['goods_id']);
            }
            else
            {
                $goods[$key]['market_price'] = self::$goodsModel->get_vip_price_for_all($value['goods_id'], 1);
                $goods[$key]['vip_price'] = self::$goodsModel->get_vip_price_for_all($value['goods_id'], 1);
                $goods[$key]['true_vip_price'] = self::$goodsModel->get_vip_price_for_all($value['goods_id']);
            }

//			秒杀价格处理
            $price = bargain_price($goodsInfo['promote_price'], $goodsInfo['promote_start_date'], $goodsInfo['promote_end_date']);
            if ($price > 0) {
                $goods[$key]['buy_now_end_date'] = date('m-d H:i', localtotime($goodsInfo['promote_end_date']));
                $goods[$key]['buy_now_start_date'] = date('m-d H:i', localtotime($goodsInfo['promote_start_date']));

                $goods[$key]['buy_now_end_time'] = localtotime($goodsInfo['promote_end_date']);
                $goods[$key]['buy_now_start_time'] = self::buyNowTimeRand($goodsInfo['promote_start_date']);

                $goods[$key]['buy_now_goods_number'] = $goodsInfo['promote_goods_number'];
                $goods[$key]['buy_now_today_number'] = $goodsInfo['promote_today_number'];

                $goods[$key]['buy_now_price'] = $price;
            }
            else
            {
                $goods[$key]['buy_now_price'] = 0;
                $goods[$key]['buy_now_end_date'] = '';
                $goods[$key]['buy_now_start_date'] = '';
            }

//			秒杀状态处理
            $goods[$key]['buy_now_status'] = self::handleBuyNowGoods($goodsInfo);
        }

        return $goods;
    }

    /**
     * 获取秒杀价格数据
     * Created by Jerry
     * @param $goods
     * @return mixed
     */
    public function getBuyNowGoodsData($goods)
    {
//			秒杀价格处理
        $price = $this->checkBuyNowPrice($goods);
//        dd($price);
        if ($price > 0) {

            $goods['buy_now_end_date'] = date('Y-m-d H:i:s', localtotime($goods['promote_end_date']));
            $goods['buy_now_start_date'] = date('Y-m-d H:i:s', localtotime($goods['promote_start_date']));



            $goods['buy_now_end_time'] = localtotime($goods['promote_end_date']);
            $goods['buy_now_start_time'] = self::buyNowTimeRand($goods['promote_start_date']);

            $time = time();
            $goods['start_time_sec'] = $goods['buy_now_start_time'] > $time ? $goods['buy_now_start_time'] - $time : 0;
            $goods['end_time_sec'] = $goods['buy_now_end_time'] > $time && $goods['buy_now_start_time'] < $time ? $goods['buy_now_end_time'] - $time : 0;

            $goods['buy_now_goods_number'] = $goods['promote_goods_number'];
            $goods['buy_now_today_number'] = $goods['promote_today_number'];
            $goods['buy_now_user_rank'] = $goods['promote_user_rank'];

            $goods['buy_now_price'] = $price;

//			秒杀状态处理
            $goods['buy_now_status'] = self::handleBuyNowGoods($goods);

            $goods['promote_price'] = 0;
//			$goods['promote_start_date'] = '';
//			$goods['promote_end_date'] = '';
//			$goods['promote_goods_number'] = 0;
//			$goods['promote_today_number'] = 0;
//			$goods['promote_user_rank'] = 0;
        }

        return $goods;
    }

    /**
     * Created by Jerry
     * @param $goods
     * @return mixed
     */
    public function formatBuyNowGoodsData($goods)
    {
//			秒杀价格处理
        $price = $this->checkBuyNowPrice($goods);

        $goods['market_price'] = self::$goodsModel->get_vip_price_for_all($goods['goods_id'], 1);

        $goods['is_presell'] = ($goods['is_presell'] == 1) ? self::$goodsStorageModel->check_whether_presell($goods['goods_id'], $this->wid) : $goods['is_presell'];

        $goods['buy_now_notice'] = self::$buyNowNoticeService->isNotice($this->userId, $goods['goods_id']);

        $goodsNumber = $this->findGoodsStorageById($goods['goods_id']);

        if ($goods['is_presell'] == 0) {
//				现售商品使用实际库存
            $goods['goods_number'] = $goodsNumber;
        }


        $goods = $this->bookingTime($goods);

        if ($goods['goods_number'] == 0) {
            $goods['is_book_goods'] = $this->goodsBook($goods['goods_id']);
        }

        $goods['buy_now_end_date'] = date('Y-m-d H:i:s', localtotime($goods['promote_end_date']));
        $goods['buy_now_start_date'] = date('Y-m-d H:i:s', localtotime($goods['promote_start_date']));

        $goods['buy_now_date_key'] = $keyDate = date('H:00', localtotime($goods['promote_start_date']));
        $goods['buy_now_time_key'] = strtotime($keyDate);

        $goods['buy_now_end_time'] = localtotime($goods['promote_end_date']);
        $goods['buy_now_start_time'] = self::buyNowTimeRand($goods['promote_start_date']);

        $goods['buy_now_goods_number'] = $goods['promote_goods_number'];
        $goods['buy_now_today_number'] = $goods['promote_today_number'];

        $goods['buy_now_price'] = $price;

        $this->message = array();
        $goods['buy_now_message'] = $this->thenBuyNowGoodsLimitMessage($goods)->getLimitMessage();

//			秒杀状态处理
        $goods['buy_now_status'] = self::handleBuyNowGoods($goods);

//		unset($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date'], $goods['promote_goods_number'], $goods['promote_today_number']);

        $goods['promote_price'] = 0;
        $goods['promote_start_date'] = '';
        $goods['promote_end_date'] = '';
        $goods['promote_goods_number'] = 0;
        $goods['promote_today_number'] = 0;

        return $goods;
    }

    /**
     * 预售最早发货时间
     * Created by Jerry
     * @param $goods
     * @return mixed
     */
    protected function bookingTime($goods)
    {
        if ($goods['is_presell']) {
            if ($goods['delivery_type'] == 1) {
                if (self::$goodsPresellTimeModel->check_shipping_goodspreselltime($goods['goods_id'])) {
                    $time = time();
                    $shippingTime = self::$goodsPresellTimeModel->check_shippingtime($goods['goods_id'], $time);

                    if ($shippingTime) {
                        $goods['preselltimeres'] = array(
                            'delivery_time' => $shippingTime,
                        );
                    } else {
                        $goods['preselltimeres'] = array(
                            'delivery_time' => '',
                        );
                    }
                } else {
                    $goods['preselltimeres'] = array(
                        'delivery_time' => '',
                    );
                }
            } else if ($goods['delivery_type'] == 2) {
                if ($goods['delivery_cycle']>=0) {
                    $gmd = local_date('Y-m-d', gmtime());

                    $goodsPresellTime = local_date('Y-m-d H:i:s', local_strtotime($gmd . ' +' . $goods['delivery_cycle'] . ' day ' . C('DEFAULT_PRESELL_TIME_H')));
                    $goods['preselltimeres'] = array(
                        'delivery_time' => $goodsPresellTime,
                    );
                } else {
                    $goods['preselltimeres'] = array(
                        'delivery_time' => '',
                    );
                }
            } else {
                $goods['preselltimeres'] = array(
                    'delivery_time' => '',
                );
            }
        } else {
            $goodsStorage = self::$goodsStorageModel->get_warehous_goods($this->wid, $goods['goods_id']);
            if ($goodsStorage) {
                $goods['goods_number'] = $goodsStorage['practical_num'];
            } else {
                $goods['goods_number'] = 0;
            }
            $goods['preselltimeres'] = array(
                'delivery_time' => '',
            );
        }

        return $goods;
    }

    /**
     * 返回延长时间
     * Created by Jerry
     * @param $time
     * @return int
     */
    static protected function buyNowTimeRand($time)
    {
        return localtotime($time);
    }

    /**
     * 检测秒杀价是否生效
     * Created by Jerry
     * @param $goods
     * @return bool
     */
    public function checkBuyNowPrice($goods)
    {
        if (empty($goods) || $goods['is_buynow'] == 0) {
            return false;
        }

        return $goods['promote_price'];
    }

    /**
     * 获取秒杀状态
     * Created by Jerry
     * @param $goods
     * @return bool|int
     */
    public function getBuyNowGoodsStatus($goods)
    {
        if (empty($goods)) {
            return false;
        }

        return self::handleBuyNowGoods($goods);
    }

    /**
     * 处理秒杀类型
     * Created by Jerry
     * @param $goods
     * @return int
     */
    static protected function handleBuyNowGoods($goods)
    {
        $type = 0;
        $time = gmtime();

//		已过期
        if ($goods['promote_end_date'] < $time) {
            $type = 1;
        }

//		未开始
        if ($goods['promote_start_date'] > $time) {
            $type = 2;
        }

//		进行中
        if ($goods['promote_start_date'] < $time && $goods['promote_end_date'] > $time) {
            $type = 3;
        }

        return $type;
    }

    /**
     * 返回商品详情
     * Created by Jerry
     * @param $goodsId
     * @return mixed
     */
    public function findBuyNowGoodsInfoByGoodsId($goodsId)
    {
        return self::$goodsWidModel->setTableNameByWid($this->wid)->findBuyNowGoodsInfoByGoodsId($goodsId);
    }

    /**
     * Created by Jerry
     * @param $goodsId
     * @return int
     */
    public function getGoodsStorageGoodsNumber($goodsId)
    {
        return self::$goodsStorageModel->check_whether_presell($goodsId, $this->wid);
    }

    /**
     * 返回指定id库存数量
     * Created by Jerry
     * @param $id
     * @return mixed
     */
    protected function findGoodsStorageById($id)
    {
        $data = self::$goodsStorageModel->get_warehous_goods($this->wid, $id);

        return $data['practical_num'] + 0;
    }

    /**
     * 返回订阅数据
     * Created by Jerry
     * @param $goodsId
     * @return int
     */
    protected function goodsBook($goodsId)
    {
        $rs = self::$goodsModel->is_book_goods($goodsId, $this->userId, 0);

        if ($rs) {
            return 1;
        }

        return 0;
    }

    /**
     * Created by Jerry
     * @param $cartId
     * @param $updateData
     * @return bool
     */
    public function updateBuyNowGoodsCartDataByCartId($cartId, $updateData)
    {
        $where = array(
            'rec_id'	=>	$cartId,
        );

        return M('cart')->where($where)->save($updateData);
    }

    /**
     * Created by Jerry
     * @param $goods
     * @return $this
     */
    protected function thenBuyNowGoodsLimitMessage($goods)
    {
        $time = gmtime();
        if ($goods['promote_start_date'] < $time &&  $goods['promote_end_date'] < $time) {
//			秒杀商品已过期
            array_push($this->message, '');
            return $this;
        }

        if ($goods['promote_start_date'] > $time &&  $goods['promote_end_date'] > $time) {
//			秒杀商品未开始
            array_push($this->message, '');
            return $this;
        }

        if ($goods['promote_goods_number'] > 0) {
            array_push($this->message, '每单限购' . $goods['promote_goods_number'] . '份');
        }

        if ($goods['promote_today_number'] > 0) {
            array_push($this->message, '每天限购' . $goods['promote_today_number'] . '单');
        }

        if ($goods['promote_today_number'] == '-1') {
            array_push($this->message, '每人限购1单');
        }

        return $this;
    }

    /**
     * Created by Jerry
     * @return string
     */
    public function getLimitMessage()
    {
        $message = implode(',', $this->message);
        return trim($message, ',');
    }

    /**
     * Created by Jerry
     * @param $name
     * @param $value
     * @return $this
     */
    public function __set($name, $value)
    {
        $this->$name = $value;
        return $this;
    }

}